<?php
namespace Admin\Model;
use Think\Model;

class ModelModel extends Model {
	//创建表模型
	public function _create($tablename) {
		$Model = new \Think\Model();
		$dbname = C('DB_NAME');
		if (!$tablename) {
			return false;
		} else {
			$table = C('DB_PREFIX') . $tablename;
		}
		;

		return $Model->execute("CREATE TABLE `{$dbname}`.`{$table}` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '自动记录创建时间' , `update_time` VARCHAR(20) NULL COMMENT '更新时间' ,`state` INT(10) NULL COMMENT '文档状态' ,`sort` SMALLINT(10) NULL COMMENT '排序' , `browse` SMALLINT(200) NULL COMMENT '浏览记录' ,`uid` SMALLINT(10) NULL COMMENT '用户id' ,PRIMARY KEY (`id`)) ENGINE = MyISAM");

	}
	//检查是否存在该字段
	public function is_field($table, $name) {
		if (!$name) {
			return false;
		}
		if (!$table) {
			return false;
		}
		$fields = M($table)->getDbFields();

		if (array_search($name, $fields)) {
			return true;
		} else {
			return false;
		}

	}
	// 新增字段
	public function _create_field($table, $name, $length, $comment, $type) {
		$Model = new \Think\Model();
		if ($table) {
			$tablename = C('DB_PREFIX') . $table;
		}
		$typ = $type . '(' . $length . ')';
		switch ($typ) {
		case 'text':
			return $Model->execute("ALTER TABLE `{$tablename}` ADD `{$name}` {$type}  NULL COMMENT '{$comment}' AFTER `id`");
			break;

		default:
			return $Model->execute("ALTER TABLE `{$tablename}` ADD `{$name}` {$typ}  NULL COMMENT '{$comment}' AFTER `id`");
			break;
		}

	}
	//删除字段
	public function del_field($table, $name) {
		if ($table) {
			$tablename = C('DB_PREFIX') . $table;
		}
		$Model = new \Think\Model();
		return $Model->execute("ALTER TABLE `{$tablename}` DROP `{$name}`");
	}
	//删除表
	public function delmodel($table) {
		if (!$table) {
			return false;
		} else {
			$tablename = C('DB_PREFIX') . $table;
		}

		$Model = new \Think\Model();
		return $Model->execute("DROP TABLE `{$tablename}`");
	}
	//转换成拼音
	public function _pinyin($title, $type = 'head') {
		if ($title) {
			return \Think\pinyin::encode($title, $type);
		}

	}
	//以下是模型模板
	public function lists($id) {
		if (!$id) {
			return false;
		}
		return list_sort_by(cache_table('require', array('modelid' => $id)), 'sort');

	}
	/*
		$number int 模型id
		$docid  int 要修改的文章id
		$table  bool 以table显示信息
	*/
	public function FormLayout($number, $docid, $table, $rollback) {
		$loyout = $this->lists($number);

		//是否修改数据
		if (is_int($docid)) {
			$map['id'] = $docid;
			$model = GetModelTable($number);
			if ($model) {
				$data = M($model)->where($map)->find();
			}
		}
		if ($table) {
			$type[] = array('title' => '查看详情', 'url' => 'show', 'class' => 'default', 'type' => 'show');
			return getTables($number, $type, array('id' => $docid), true);
			//return $this->ShowTable($number, $data);

		}
		//回滚添置
		if ($rollback) {
			$html .= $rollback;
		}
		//按类型显示对应模板
		for ($i = 0; $i < count($loyout); $i++) {
			if ($loyout[$i]['value'] == '*') {
				unset($loyout[$i]['value']);
			}
			switch ($loyout[$i]['type']) {
			case 'text|varchar':
				/*
					$loyout[$i]  array 对应的数据
					$data        array 要修改的数据
				*/
				$html .= $this->_text($loyout[$i], $data);
				break;
			case 'number|smallint':
				$html .= $this->_text($loyout[$i], $data);
				break;
			case 'number|float':
				$html .= $this->_float($loyout[$i], $data);
				break;
			case 'file|text':
				$html .= $this->_file($loyout[$i], $data);
				break;
			case 'radio|varchar':
				$html .= $this->_radio($loyout[$i], $data);
				break;
			case 'select|varchar':
				$html .= $this->_dow_select($loyout[$i], $data);
				break;
			case 'select|char':
				$html .= $this->_dow_select_model($loyout[$i], $data);
				break;
			case 'checkbox|varchar':
				$html .= $this->_checkbox($loyout[$i], $data);
				break;
			case 'link|varchar':
				$html .= $this->_select($loyout[$i], $data);
				break;
			case 'city|varchar':

				$html .= $this->_city($loyout[$i], $data);
				break;
			case 'textarea|text':
				$html .= $this->_textarea($loyout[$i], $data);
				break;
			case 'textarea|varchar':
				$html .= $this->_textarea_varchar($loyout[$i], $data);
				break;
			case 'date|varchar':
				$html .= $this->_date($loyout[$i], $data);
				break;
			default:
				$html .= $loyout[$i]['type'] . '该类型模板不存在';
				break;
			}
		}

		return $html;
	}
	/*
		return  html table表格信息
	*/
	private function ShowTable($number, $data) {

		$html .= "<table class='table table-hover table-bordered'>";
		//按类型显示对应模板
		for ($i = 0; $i < count($loyout); $i++) {
			if ($loyout[$i]['value'] == '*') {
				unset($loyout[$i]['value']);
			}

			switch ($loyout[$i]['type']) {
			// case 'text|varchar':
			// 	/*
			// 		$loyout[$i]  array 对应的数据
			// 		$data        array 要修改的数据
			// 	*/

			case 'file|text':
				$html .= "<tr>";
				$html .= "<td>{$loyout[$i]['name']}</td>";
				$html .= "<td>";
				if ($data[$loyout[$i]['field']]) {
					$temp = "{$data[$loyout[$i]['field']]}";
					$default = json_decode($temp, true);
					if (is_array($default)) {
						for ($k = 0; $k < count($default['alt']); $k++) {
							$html .= "<img src='{$default['path'][$k]}'>";
						}
					}
				}
				$html .= "</td>";
				$html .= "</tr>";
				break;

			case 'checkbox|varchar':
				$html .= "<tr>";
				$html .= "<td>{$loyout[$i]['name']}</td>";
				$html .= "<td>";
				if ($data[$loyout[$i]['field']]) {
					$temp = "{$data[$loyout[$i]['field']]}";
					$default = json_decode($temp, true);
					if (is_array($default)) {
						for ($k = 0; $k < count($default); $k++) {
							$html .= "{$default[$k]}|";
						}
					}
				}
				$html .= "</td>";
				$html .= "</tr>";
				break;
			case 'link|varchar':
				$data_value = json_decode($data[$value['field']]);

				$html .= "<tr>";
				$html .= "<td>{$loyout[$i]['name']}</td>";
				$html .= "<td>{$data[$loyout[$i]['field']]}</td>";
				$html .= "</tr>";

				break;

			default:
				$html .= "<tr>";
				$html .= "<td>{$loyout[$i]['name']}:</td>";
				$html .= "<td>{$data[$loyout[$i]['field']]}</td>";
				$html .= "</tr>";

				break;
			}
		}
		$html .= "</table>";
		return $html;
	}

	/*
		*post提交的数据和模型数据对接
		*$number模型id
		*$docid int 文档id
		return bool  是否提效成功
	*/
	public function ModelDataJson($number, $docid) {

		if (!$number) {
			return false;
		}
		$post = I('post.');
		// $post = $_POST;
		//模型条件数据

		$modeldata = $this->lists($number);

		//按条件组合数据
		foreach ($modeldata as $key => $value) {
			switch ($modeldata[$key]['type']) {
			case 'date|varchar':

				$post[$modeldata[$key]['field']] = strtotime($post[$modeldata[$key]['field']]);
				break;
			case 'textarea|text':
				$post[$modeldata[$key]['field']] = htmlspecialchars($_POST[$modeldata[$key]['field']]);
				break;
			default:

				if (is_array($post[$modeldata[$key]['field']])) {

					$post[$modeldata[$key]['field']] = json_encode($post[$modeldata[$key]['field']]);
				} else {

					if (!$post[$modeldata[$key]['field']]) {
						//删除为空值
						unset($post[$modeldata[$key]['field']]);
					} else {
						$post[$modeldata[$key]['field']] = $post[$modeldata[$key]['field']];
					}

				}
				break;
			}
		}

		// return $post;
		// //获取模型表名
		$model = GetModelTable($number);

		if ($model) {
			//文档id是否存在
			if (is_int($docid)) {
				$post['update_time'] = time(); //记录更新时间
				if (M($model)->where(array('id' => $docid))->save($post)) {
					$data['status'] = true;
					$data['info'] = '更新成功';
					return $data;
				} else {
					$data['status'] = false;
					$data['info'] = '更新失败';
					return $data;
				}

			} else {
				$create_model = M($model);
				//新增数据审核状态
				$post['state'] = document_state();
				//用户id
				$post['uid'] = session('auth.id');
				if ($create_model->create($post, 1)) {
					$result = $create_model->data($post)->add();

					if ($result) {
						$data['status'] = true;
						$data['info'] = '保存成功';
					} else {
						$data['status'] = false;
						$data['info'] = '保存失败';
					}
					return $data;
				}

			}

		}

	}

	//文本类型
	private function _text($value, $data) {

		$type = explode('|', $value['type']);
		$html .= "<div class='form-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		if (!$value['control']) {
			$ignore = "ignore='ignore'";
		}
		//是否存在要修改的值
		if ($data[$value['field']]) {
			$default = "value='{$data[$value['field']]}'";
		} else {
			$default = "value='{$value['value']}'";
		}
		$html .= "<input type='{$type['0']}' name='{$value['field']}' nullmsg='{$value['name']}必须填写' datatype='{$value['require']}' placeholder='{$value['value']}' $ignore class='form-control col-sm-10' {$default}>";
		$html .= "</div>";
		return $html;
	}
	//浮点类型
	private function _float($value, $data) {

		$type = explode('|', $value['type']);
		$html .= "<div class='input-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		if (!$value['control']) {
			$ignore = "ignore='ignore'";
		}
		//是否存在要修改的值
		if ($data[$value['field']]) {
			$default = "value='{$data[$value['field']]}'";
		} else {
			$default = "value='{$value['value']}'";
		}
		$html .= "<input aria-describedby='basic-addon2' type='{$type['0']}' name='{$value['field']}' id='{$value['field']}' nullmsg='{$value['name']}必须填写' datatype='{$value['require']}' placeholder='{$value['value']}' href=" . U('Login/getPrice') . " class='form-control float' {$default}>";
		$html .= "<span class=\"input-group-btn\"><button class=\"btn btn-default\" type=\"button\" style='margin-top: 26px;'><span class='text-danger Capital'>零</span></button></span>";
		$html .= "</div>";
		return $html;
	}
	//时间类型
	private function _date($value, $data) {
		$type = explode('|', $value['type']);
		$html .= "<div class='form-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		if (!$value['control']) {
			$ignore = "ignore='ignore'";
		}
		//是否存在要修改的值
		if ($data[$value['field']]) {
			$time = date('Y-m-d', $data[$value['field']]);

			$default = "value='{$time}'";

		} else {
			$time = date('Y-m-d', $value['value']);
			// $default = "value='{$time}'";
		}
		$html .= "<div class='input-group'>";
		$html .= "<span class='input-group-addon' id='basic-addon1'><i class='glyphicon glyphicon-calendar'></i></span>";
		$html .= "<input type='text' {$default} name='{$value['field']}'  placeholder='{$value['value']}' class='form-control datatime' style='width:200px' id='{$value['field']}' {$ignore}>";
		$html .= "</div>";
		$html .= "</div>";
		return $html;
	}
	//多行文本
	private function _textarea_varchar($value, $data) {
		$type = explode('|', $value['type']);
		$style = explode(',', $value['value']);
		if (count($style) == 2) {
			$sty = "style=\"width:{$style['0']}px;height:{$style['1']}px\"";

		} else {
			$sty = "rows='3'";
			$defaultvalue = "{$value['value']}";
		}
		$html .= "<div class='form-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		if (!$value['control']) {
			$ignore = "ignore='ignore'";
		}
		//是否存在要修改的值
		if ($data[$value['field']]) {
			$default = "{$data[$value['field']]}";
		}
		$html .= "<textarea class=\"form-control\" {$sty} name='{$value['field']}' id='{$value['field']}' nullmsg='{$value['name']}必须填写' datatype='{$value['require']}' {$ignore} placeholder='{$defaultvalue}'>{$default}</textarea>";

		$html .= "</div>";

		return $html;
	}
	//文本编缉器
	private function _textarea($value, $data) {

		$type = explode('|', $value['type']);
		$style = explode(',', $value['value']);
		if (count($style) == 2) {
			$sty = "style=\"width:{$style['0']}px;height:{$style['1']}px\"";

		} else {
			$sty = "rows='3'";
			$defaultvalue = "{$value['value']}";
		}
		$html .= "<div class='form-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		// if (!$value['control']) {
		// 	$ignore = "ignore='ignore'";
		// }
		//是否存在要修改的值
		if ($data[$value['field']]) {
			$default = "{$data[$value['field']]}";
		}
		$html .= "<textarea class=\"form-control textarea\" {$sty} name='{$value['field']}' id='{$value['field']}' placeholder='{$defaultvalue}'>{$default}</textarea>";

		$html .= "</div>";

		return $html;
	}
	//图片上传
	private function _file($value, $data) {
		$type = explode('|', $value['type']);
		$html .= "<div class='form-group'>";
		$html .= "<label for='{$value['field']}'>{$value['name']}<span class='Validform_checktip'></span></label>";
		// if (!$value['control']) {
		// 	$ignore = "ignore='ignore'";
		// }
		$html .= "<input type='{$type['0']}' title='{$value['name']}' name='{$value['field']}' href=" . U('Login/Upload') . " id='{$value['field']}' class='uploads' placeholder='{$value['value']}' multiple='true'>";
		if ($data[$value['field']]) {
			$temp = "{$data[$value['field']]}";
			$default = json_decode($temp, true);
			if (is_array($default)) {
				for ($i = 0; $i < count($default['alt']); $i++) {
					$html .= "<div class='uploadifive-queue' id='uploadifive-{$value['field']}-queue'>";
					$html .= "<div class='uploadifive-queue-item complete' id='uploadifive-{$value['field']}-file-{$i}'><span class='filename'><input type='text' value='{$default['alt'][$i]}' name='{$value['field']}[alt][]'><input type='hidden' value='{$default['path'][$i]}' name='{$value['field']}[path][]'></span> | <span class='fileinfo'>上传成功</span>";
					$html .= "<div class='close'></div>";
					$html .= "</div>";
					$html .= "</div>";
				}
			}
		}

		$html .= "</div>";
		return $html;
	}
	//单选
	private function _radio($value, $data) {
		$foreach = explode(',', $value['value']);
		$html .= "<div class='form-group' id='{$value['field']}'>";
		$html .= "<label class='control-label valtype' style='display:block'>{$value['name']}<span class='Validform_checktip'></span></label>";
		for ($i = 0; $i < count($foreach); $i++) {
			$html .= "<label class='radio-inline'>";
			//
			if (!$value['control']) {
				$ignore = "ignore='ignore'";
			}

			if ($data[$value['field']] == $foreach[$i]) {

				$html .= "<input type='radio' checked='checked' {$ignore} datatype='{$value['require']}' name='{$value['field']}'  value='{$foreach[$i]}'>{$foreach[$i]}";

			} else {
				$html .= "<input type='radio' {$ignore} datatype='{$value['require']}' name='{$value['field']}'  value='{$foreach[$i]}'>{$foreach[$i]}";
			}

			$html .= "</label>";
		}
		$html .= "</div>";
		return $html;
	}
	//多选
	private function _checkbox($value, $data) {

		$foreach = explode(',', $value['value']);
		$html .= "<div class='form-group' id='{$value['field']}'>";
		$html .= "<label class='control-label valtype' style='display:block'>{$value['name']}</label>";
		for ($i = 0; $i < count($foreach); $i++) {
			$html .= "<label class='checkbox-inline'>";
			if (in_array($foreach[$i], json_decode($data[$value['field']]))) {
				$html .= "<input type='checkbox' name='{$value['field']}[]' checked='checked' value='{$foreach[$i]}'>{$foreach[$i]}";
			} else {
				$html .= "<input type='checkbox' name='{$value['field']}[]' value='{$foreach[$i]}'>{$foreach[$i]}";
			}

			$html .= "</label>";
		}

		$html .= "</div>";
		return $html;
	}
	//联动模型
	private function _select($value, $data) {
		$data_value = json_decode($data[$value['field']]);
		$html .= "<div class='form-group linkmodel' id='{$value['field']}' href='" . U('Model/link', array('id' => $value['value'])) . "'>";
		$html .= "<label class='control-label valtype' data-valtype='label'>{$value['name']}</label>";
		$html .= "<div class='controls'>";
		if ($data_value['0']) {
			$val = "data-value='{$data_value['0']}'";
		}
		$html .= "<select class='input-xlarge valtype province' data-first-title='请选择' name='{$value['field']}[]' {$val}>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		if ($data_value['1']) {
			$val1 = "data-value='{$data_value['1']}'";
		}
		$html .= "<select class='input-xlarge valtype city' data-first-title='请选择' name='{$value['field']}[]' {$val1}'>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		if ($data_value['2']) {
			$val2 = "data-value='{$data_value['2']}'";
		}
		$html .= "<select class='input-xlarge valtype area' data-first-title='请选择' name='{$value['field']}[]' {$val2}>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		$html .= "</div>";
		$html .= "</div>";

		return $html;
	}
	//联动模型
	private function _city($value, $data) {
		$data_value = json_decode($data[$value['field']]);
		$html .= "<div class='form-group linkcity' id='{$value['field']}' href='" . __APP__ . '/Public/cxselect/cityData.min.json' . "'>";
		$html .= "<label class='control-label valtype' data-valtype='label'>{$value['name']}</label>";
		$html .= "<div class='controls'>";
		if ($data_value['0']) {
			$val = "data-value='{$data_value['0']}'";
		}
		$html .= "<select class='input-xlarge valtype province' data-first-title='请选择' name='{$value['field']}[]' {$val}>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		if ($data_value['1']) {
			$val1 = "data-value='{$data_value['1']}'";
		}
		$html .= "<select class='input-xlarge valtype city' data-first-title='请选择' name='{$value['field']}[]' {$val1}'>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		if ($data_value['2']) {
			$val2 = "data-value='{$data_value['2']}'";
		}
		$html .= "<select class='input-xlarge valtype area' data-first-title='请选择' name='{$value['field']}[]' {$val2}>";
		$html .= "<option selected></option>";
		$html .= "</select>";
		$html .= "</div>";
		$html .= "</div>";

		return $html;
	}
	//关联表模型
	private function _dow_select_model($value, $data) {

		$foreach = explode(',', $value['value']);
		if (!is_array($foreach)) {
			return '关联表模型值错误';
		}
		$model = GetModelTable($foreach['0']);
		$fields = $foreach['1'];
		if ($model) {
			$show = M($model)->where(array('id' => $data[$value['field']]))->field('id,' . $fields)->find();

		}
		$html .= "<div class='form-group'>";
		$html .= "<label class='control-label'>{$value['name']}<span class='Validform_checktip'></span></label>";
		$html .= "<div class='controls'>";
		if ($value['control']) {
			$ignore = "ignore='ignore'";
		}
		$html .= "<div class='input-group'>";
		$html .= "<span class='input-group-addon' id='basic-addon1'><i class='glyphicon glyphicon-align-justify'></i></span>";
		if ($show) {
			$html .= "<input value='{$show[$foreach['1']]}' type='text' class='form-control linktable' selected='{$foreach['1']}' href=" . U('Model/linktable', array('mid' => $foreach['0'], 'field' => $value['field'], 'selected' => $foreach['1'])) . " style='width:200px'  datatype='*' id='{$value['field']}' {$ignore}>";
			$html .= "<input value='{$show['id']}' type='hidden' name='{$value['field']}'>";
		} else {
			$html .= "<input type='text' class='form-control linktable' selected='{$foreach['1']}' href=" . U('Model/linktable', array('mid' => $foreach['0'], 'field' => $value['field'], 'selected' => $foreach['1'])) . " style='width:200px'  datatype='*' id='{$value['field']}' {$ignore}>";
			$html .= "<input type='hidden' name='{$value['field']}'>";
		}

		$html .= "</div>";

		$html .= "</div>";
		$html .= "</div>";
		return $html;
	}
	//下拉菜单
	private function _dow_select($value, $data) {
		$foreach = explode(',', $value['value']);
		$html .= "<div class='form-group' id='{$value['field']}'>";
		$html .= "<label class='control-label'>{$value['name']}<span class='Validform_checktip'></span></label>";
		$html .= "<div class='controls'>";
		if ($value['control']) {
			$ignore = "ignore='ignore'";
		}
		$html .= "<select  class='selectpicker' name='{$value['field']}' datatype='{$value['require']}' {$ignore}>";
		for ($i = 0; $i < count($foreach); $i++) {
			if ($data[$value['field']] == $foreach[$i]) {
				$selected = "selected='selected'";
				$html .= "<option type='radio' {$selected} name='{$value['field']}' value='{$foreach[$i]}'>{$foreach[$i]}</option>";
			} else {
				$html .= "<option type='radio' name='{$value['field']}' value='{$foreach[$i]}'>{$foreach[$i]}</option>";
			}

		}
		//
		$html .= "</select>";
		$html .= "</div>";
		$html .= "</div>";
		return $html;
	}

}